-- UISummonBlacksmith
-- Created by cheny3 Dec/15/2016
-- 召唤兽工坊

UISummonBlacksmith = class("UISummonBlacksmith", function()
    return cc.Layer:create();
end);

function UISummonBlacksmith.create(gridData)
    return UISummonBlacksmith.new(gridData);
end

-- 制作动画播放时间
local PRODUCE_TIME = 0.6;

-- 制作完成后，界面停留的时间
local STAY_TIME = 0.6;

function UISummonBlacksmith:ctor(gridData)
    -- 初始化
    self:setName("UISummonBlacksmith");
    local node = cc.CSLoader:createNode("layout/lab/DungeonLab.csb");
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    -- 记录格子数据
    self.gridData = gridData;

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 重绘
    self:redrawMain();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 适配
    self:resize();
end

-- 适配
function UISummonBlacksmith:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 注册事件处理回调函数
function UISummonBlacksmith:registerEventCallback()
    -- 关注实验台升级的事件
    EventMgr.register("UISummonBlacksmith", event.SUMMON_BLACKSMITH_UPGRADE, function(args)
        local id = args.id;

        local function showHint()
            -- 成功了
            alert(SummonBlacksmithM.queryBonus(id, "bonus_tip"));

            -- 播放奖励特效
            self:playBonusEffect(id);
        end

        performWithDelay(self, showHint, STAY_TIME - 0.05);
    end);

    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            cclog("UISummonBlacksmith 界面析构清理");

            -- 移除所有事件关注
            EventMgr.removeAll("UISummonBlacksmith");

            if UIDungeonMgr:getCurLevel() then
                UIDungeonMgr:getCurLevel():showMenu();
            end

        elseif eventType == "enter" then
            if UIDungeonMgr:getCurLevel() then
                UIDungeonMgr:getCurLevel():hideMenu();
            end
        end
    end);
end

-- 注册点击事件
function UISummonBlacksmith:registerTouchEvent()
    -- 注册返回按钮点击事件
    local node = self.node;
    local btnBack = findChildByName(node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            if self.id then
                -- 返回上一界面
                self.id = nil;
                self:redrawMain();
            else
                -- 关闭当前界面
                UIMgr.getCurrentScene():removeFormByName("UISummonBlacksmith");
            end
            AudioM.playFx("button_return");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册确定按钮点击事件
    local btnOk = findChildByName(node, "CT/btn_ok");
    local function onOkClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");

            -- 判断材料是否足够
            local cost = SummonBlacksmithM.queryBonus(self.id, "cost");
            if not self:checkCost(cost) then
                alert(getLocStr("forge_spade_material_lock"));
                return;
            end

            if not SummonBlacksmithM.canCureSummon(self.id) then
                alert(SummonBlacksmithM.queryBonus(self.id, "fail_tip"));
                return;
            end

            -- 按钮短暂置灰
            setClickFrequency(sender, PRODUCE_TIME + 0.7);

            -- 播放制作动画
            self:playProduceEffect();

            local function doCompound()
                -- 升级
                local pos = self.gridData:getPos();
                DungeonActionM.go("summon_blacksmith_upgrade", pos, self.id);
            end
            performWithDelay(self, doCompound, PRODUCE_TIME);
        end
    end
    btnOk:addTouchEventListener(onOkClick);

    -- 四个按钮
    local moreBtnNode = findChildByName(self.node, "CT/more_btn");
    local blacksmithId = self.gridData.blacksmith_id;
    local upgrades = SummonBlacksmithM.query(blacksmithId, "upgrades");
    for index, id in ipairs(upgrades) do
        local btnNode = findChildByName(moreBtnNode, "btn" .. index);
        local info = SummonBlacksmithM.queryBonus(id);
        local function onBtnClick(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                AudioM.playFx("button_click");
                -- 重绘界面
                self.id = btnNode.id;
                self:redraw();
            end
        end
        btnNode:addTouchEventListener(onBtnClick);
    end
end

-- 播放奖励特效
function UISummonBlacksmith:playBonusEffect(id)
    -- 移除制作特效
    self:removeProduceEffect();
    self:redraw();

    -- 关闭界面
    local function playAnim()
        -- 关闭界面/不关闭界面
        -- UIMgr.getCurrentScene():removeFormByName("UISummonBlacksmith");
    end

    -- 短暂停留
    performWithDelay(self, playAnim, STAY_TIME);
end

-- 移除制作动画
function UISummonBlacksmith:removeProduceEffect()
    local effectNode = findChildByName(self.node, "CT/effect_node");
    effectNode:removeAllChildren();
end

-- 播放制作动画
function UISummonBlacksmith:playProduceEffect()
    -- 播放制作特效
    local effectNode = findChildByName(self.node, "CT/effect_node");
    playEffect(effectNode, 1151);
end

-- 绘制主界面
function UISummonBlacksmith:redrawMain()
    local descLabel  = findChildByName(self.node, "CT/desc");
    local iconImg    = findChildByName(self.node, "CT/icon");
    local titleLabel = findChildByName(self.node, "CT/title_node/title");
    local costPart = findChildByName(self.node, "CT/cost_part");
    local btnOk      = findChildByName(self.node, "CT/btn_ok");
    local moreBtnNode = findChildByName(self.node, "CT/more_btn");

    btnOk:setVisible(false);
    costPart:setVisible(false);
    moreBtnNode:setVisible(true);

    -- 查询建筑配置
    local class = self.gridData.class;
    local buildingInfo = BuildingBonusM.queryBuildingView(class);

    -- 标题
    titleLabel:setString(buildingInfo["title"]);

    -- 图片
    iconImg:loadTexture(getLevelItemIconPath(buildingInfo["icon"]));
    if not iconImg.oriPosY then
        iconImg.oriPosY = iconImg:getPositionY();
    end
    iconImg:setPositionY(iconImg.oriPosY + tonumber(buildingInfo["icon_offset_y"]));

    TextStyleM.setTextStyle(btnOk, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    TextStyleM.setArtWordTitleStyle(titleLabel);
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    applyString(descLabel, buildingInfo["dialog"]);

    -- 重绘按钮
    self:redrawBtn();
end

-- 重绘按钮
function UISummonBlacksmith:redrawBtn()
    local moreBtnNode = findChildByName(self.node, "CT/more_btn");
    local blacksmithId = self.gridData.blacksmith_id;

    local upgrades = SummonBlacksmithM.query(blacksmithId, "upgrades");
    for index, id in ipairs(upgrades) do
        local btnNode = findChildByName(moreBtnNode, "btn" .. index);
        local info = SummonBlacksmithM.queryBonus(id);
        TextStyleM.setTextStyle(btnNode, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
        btnNode:setTitleText(info["name"]);
        btnNode.id = id;
    end
end

-- 重绘
function UISummonBlacksmith:redraw()
    local descLabel  = findChildByName(self.node, "CT/desc");
    local iconImg    = findChildByName(self.node, "CT/icon");
    local titleLabel = findChildByName(self.node, "CT/title_node/title");
    local costPart = findChildByName(self.node, "CT/cost_part");
    local btnOk      = findChildByName(self.node, "CT/btn_ok");
    local moreBtnNode = findChildByName(self.node, "CT/more_btn");

    btnOk:setVisible(true);
    costPart:setVisible(true);
    moreBtnNode:setVisible(false);

    -- 强化信息
    local blacksmithInfo = SummonBlacksmithM.queryBonus(self.id);

    -- 查询建筑配置
    local class = self.gridData.class;
    local buildingInfo = BuildingBonusM.queryBuildingView(class);

    -- 标题
    titleLabel:setString(buildingInfo["title"]);
    -- 图片
    iconImg:loadTexture(getLevelItemIconPath(buildingInfo["icon"]));

    iconImg:setScale(1.0);
    TextStyleM.setTextStyle(btnOk, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    TextStyleM.setArtWordTitleStyle(titleLabel);
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    applyString(descLabel, blacksmithInfo["desc"]);

    -- 重绘消耗
    self:redrawCost(blacksmithInfo["cost"]);
    -- 按钮可点击
    btnOk:setTouchEnabled(true);
    btnOk:setBright(true);

    -- 按钮文字
    local level = SummonBlacksmithM.getUpgradeLevel(self.id);
    local viewText = blacksmithInfo["name"];
    if blacksmithInfo["type"] == "level_up" then
        -- 升级类型的
        if type(blacksmithInfo["max_level"]) == "number" and level >= blacksmithInfo["max_level"] then
            viewText = getLocStr("btn_text_max_level");
            btnOk:setTouchEnabled(false);
            btnOk:setBright(false);
        else
            viewText = string.format(getLocStr("item_bonus_format2"), blacksmithInfo["name"], level + 1);
        end
    end
    btnOk:setTitleText(viewText);
end

-- 重绘消耗
function UISummonBlacksmith:redrawCost(cost)
    local costPart = findChildByName(self.node, "CT/cost_part");

    -- 获取需求数量
    local function getNeedAmount(classId)
        if type(cost) ~= 'table' then
            return 0;
        end

        for _, arr in pairs(cost) do
            if arr[2] == classId then
                return arr[3];
            end
        end
        return 0;
    end

    -- 消耗显示
    local items = SummonBlacksmithM.queryBonus(self.id, "cost_items");
    for i, id in pairs(items) do
        local child = findChildByName(costPart, "cost_node" .. i);

        -- 显示材料图标
        local iconImg = findChildByName(child, "icon");
        local iconPath = getItemIconPath(ItemM.query(id, "icon"));
        iconImg:loadTexture(iconPath);
        iconImg:setScale(0.7);
        iconImg:setPositionY(10);
        iconImg:setPositionX(-46);

        -- 显示数量信息
        local amountLabel = findChildByName(child, "amount");
        local needAmount = getNeedAmount(id);
        local curAmount = ItemM.getAmount(ME.user, id);

        -- 消耗不足时，显示红色
        if curAmount < needAmount then
            TextStyleM.setTextStyle(amountLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_RED);
        else
            TextStyleM.setTextStyle(amountLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BEIGE);
        end

        if needAmount <= 0 then
            -- 无需消耗
            amountLabel:setString(curAmount .. "/-");
        else

            amountLabel:setString(curAmount .. "/" .. needAmount);
        end

    end
end

-- 检查消耗是否足够
function UISummonBlacksmith:checkCost(costList)
    for _, arr in pairs(costList) do
        if ItemM.getAmount(ME.user, arr[2]) < arr[3] then
            trace("UISummonBlacksmith", "物品(%d)数量不足。", arr[2]);
            return false;
        end
    end
    return true;
end

